﻿using Core;
using System.Collections.Generic;

namespace g_gongjianta
{
    /// <summary>
    /// 可以绑在Skill，Unit，Game对象上
    ///
    /// 用于管理对象的生命周期
    /// </summary>
    public class LifeCycleSystem : Core.Component, IAwake, IFrameUpdate
    {
        private readonly Dictionary<long, ILifeCycle> dict = new();
        private readonly List<long> temp = new();

        public void Awake()
        {
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            foreach (var pair in dict)
            {
                var e = pair.Value;

                if (e.IsComplete == false)
                {
                    e.Interrupt();
                }

                e.Finish();

                (e as IDispose)?.Dispose();
            }

            dict.Clear();
        }

        public void Tick()
        {
            if (IsDisposed) return;

            temp.Clear();
            foreach (var (key, obj) in dict)
            {
                obj.Tick();

                if (!obj.IsComplete) continue;

                obj.Finish();
                temp.Add(key);
            }

            for (var i = 0; i < temp.Count; i++)
            {
                var id = temp[i];
                var e = dict[id];
                (e as Component)?.Dispose();
                dict.Remove(id);
            }
        }

        public void Mount(ILifeCycle e)
        {
            if (e is not Component c) return;

            e.Start();
            dict[c.InstanceId] = e;
        }
    }
}
